<template>
   <div class="app-container" style="height: 79%;">
       <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">

               <el-form-item label="讲师名称" style="font-weight: 800;" prop="nickname">
                 <span></span>
                  <el-input
                     v-model="queryParams.nickname"
                     placeholder="请输入讲师名称"
                     clearable
                     style="width: 240px"
                  />
               </el-form-item>
               <el-form-item label="手机号码" style="font-weight: 800;" prop="phone">
                  <el-input
                     v-model="queryParams.phone"
                     placeholder="请输入手机号码"
                     clearable
                     style="width: 240px"
                  />
               </el-form-item>
               <el-form-item label="班级名称" style="font-weight: 800;" prop="classId">
                   <el-tree-select
                    accordion="true"
                    v-model="queryParams.classId"
                    :props="{ label: 'name', children: 'children',value:'classId'}"
                    :data="cacheData"
                    style="width: 240px"
                  />
               </el-form-item>
               <el-form-item>
                  <el-button type="primary" icon="Search" @click="getList" style="width: 73px; height: 28px; font-size: 10px;">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery(queryRef)" style="width: 73px; height: 28px; font-size: 10px;">重置</el-button>
               </el-form-item>
            </el-form>
      <el-row :gutter="20">
         <!--用户数据-->
         <el-col :span="30">
            <el-row :gutter="10" class="mb8">
               <el-col :span="1.5">
                  <el-button
                     style="width: 73px; height: 28px; font-size: 10px;"
                     type="primary"
                     plain
                     icon="Plus"
                     @click="handleAdd"
                     v-hasPermi="['system:user:add']"
                  >新增</el-button>
               </el-col>
               <el-col :span="1.5">
                  <el-button
                     style="width: 73px; height: 28px; font-size: 10px;"
                     type="success"
                     plain
                     icon="Edit"
                     :disabled="single"
                     @click="handleUpdate"
                     v-hasPermi="['system:user:edit']"
                  >修改</el-button>
               </el-col>
               <el-col :span="1.5">
                  <el-button
                     style="width: 73px; height: 28px; font-size: 10px;"
                     type="danger"
                     plain
                     icon="Delete"
                     :disabled="multiple"
                     @click="handleDelete"
                     v-hasPermi="['system:user:remove']"
                  >删除</el-button>
               </el-col>
               <el-col :span="1.5">
                  <el-button
                     style="width: 73px; height: 28px; font-size: 10px;"
                     type="warning"
                     plain
                     icon="Download"
                     @click="handleExport"
                     v-hasPermi="['system:user:export']"
                  >导出</el-button>
               </el-col>
               <el-col :span="1.5" style="margin-left: 980px;">
              <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top"
                v-if="search">
                <el-button circle icon="Search" @click="toggleSearch()" />
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="刷新" placement="top">
              <el-button circle icon="Refresh" @click="refresh()" />
              </el-tooltip>
             </el-col>
            </el-row>
            
         </el-col>
      </el-row>
       <!-- 列表查询 -->
       <el-table v-loading="loading" :data="classList"  @selection-change="handleSelectionChange" :header-cell-style="{ background: '#eee', color: '#909399' }">
               <template #empty v-if="classList.length == 0">
                <el-empty description="暂时还没有班级信息哦~" />
               </template>
               <el-table-column type="selection" width="50" align="center" />
               <el-table-column label="编号" align="center" key="classId" prop="classId" />
               <el-table-column label="班级名称">
                 <template #default="scope">
                  <el-tooltip class="box-item" effect="dark" content="点击查看" placement="top">
                   <span @click="classonclick(scope.row)" style="cursor: pointer;" class="class_style">{{ scope.row.className }}</span>
                  </el-tooltip>
                  </template>
                </el-table-column>
               <!-- <el-table-column label="班级名称" align="center" key="className" prop="className" :show-overflow-tooltip="true" /> -->
               <el-table-column label="阶段名称" align="center" key="levelName" prop="levelName" :show-overflow-tooltip="true" />
               <el-table-column label="目前所在" align="center" key="name" prop="name" :show-overflow-tooltip="true" />
               <el-table-column label="所带讲师" align="center" key="nickname" prop="nickname" :show-overflow-tooltip="true" />
               <el-table-column label="手机号" align="center" key="phone" prop="phone" :show-overflow-tooltip="true" />
               <el-table-column label="电子邮箱" align="center" key="email" prop="email" :show-overflow-tooltip="true" />
               <el-table-column label="创建时间" align="center" key="createTime" prop="createTime" :show-overflow-tooltip="true" />
               <el-table-column label="修改时间" align="center" key="updateTime" prop="updateTime" :show-overflow-tooltip="true"/>
               <el-table-column label="操作" align="center" width="110" class-name="small-padding fixed-width">
                  <template #default="scope">
                     <el-tooltip content="修改" placement="top" v-if="scope.row.userId !== 1">
                        <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:user:edit']"></el-button>
                     </el-tooltip>
                     <el-tooltip content="删除" placement="top" v-if="scope.row.userId !== 1">
                        <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:user:remove']"></el-button>
                     </el-tooltip>
                     <!-- <el-tooltip content="重置密码" placement="top" v-if="scope.row.userId !== 1">
                         <el-button link type="primary" icon="Key" @click="handleResetPwd(scope.row)" v-hasPermi="['system:user:resetPwd']"></el-button>
                     </el-tooltip> -->
                  </template>
               </el-table-column>
            </el-table>
   </div>
    <!-- 分页 -->
     <el-pagination
     style="margin-left: 0%;"       
     v-model:current-page="currentPage4"
     v-model:page-size="pageSize4"
     :page-sizes="[5, 10, 15, 20]"
     layout="total, sizes, prev, pager, next, jumper"
     :total="total"
     @size-change="handleSizeChange"
     @current-change="handleCurrentChange"
     background
   />
   <!-- 新增弹框 -->
   <el-dialog
   style="border-radius: var(--el-border-radius-base);"
   v-model="centerDialogVisible"
   :title="titles"
   width="500"
   align-center>

   <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" status-icon :rules="rules" label-width="auto" class="demo-ruleForm">
        
   <el-form-item v-if="titles == '修改班级'" label="班级名称" style="font-weight: 800;" prop="">
     <el-input v-model="ruleForm.className" placeholder="请选择要添加班级名称" disabled/>
   </el-form-item>

   <el-form-item v-else label="班级名称" style="font-weight: 800;" prop="className">
     <el-input v-model="ruleForm.className" placeholder="请选择要添加班级名称"/>
   </el-form-item>

   <el-form-item label="阶段" style="font-weight: 800;" prop="levelId">
     <!-- <el-input v-model="ruleForm.classId" /> -->
     <el-select v-model="ruleForm.levelId" placeholder="选择阶段" style="width: 240px; font-weight: 400;" @change="lpIdcitiesfun(ruleForm.levelId)">
   <el-option
     v-for="item in levelIdcities"
     :key="item.id"
     :label="item.levelName"
     :value="item.id">
   </el-option>
 </el-select>
   </el-form-item>

   <el-form-item label="具体阶段" style="font-weight: 800;" prop="lpId">  
   <el-select v-model="ruleForm.lpId" placeholder="选择具体阶段" style="width: 240px; font-weight: 400;" >
   <el-option
    
     v-for="item in ff"
     :key="item.id"
     :label="item.name"
     :value="item.id">
   </el-option>
    <template #empty v-if="ff.length == 0">
      <span style="color: red;">请先选择一个阶段哦~</span>
    </template>
   </el-select>
   </el-form-item> 

   <el-form-item label="讲师" style="font-weight: 800;" prop="teacherId">
     <el-select v-model="ruleForm.teacherId"  clearable placeholder="选择所带讲师" style="width: 240px; font-weight: 400;">
   <el-option
     v-for="item in teachercities"
     :key="item.userId"
     :label="item.nickname"
     :value="item.userId">
   </el-option>
     </el-select>
   </el-form-item>
   <el-form-item>
     <el-button type="primary" @click="submitForm_class(ruleFormRef)">
       确认
     </el-button>
     &nbsp;&nbsp;&nbsp;
     <span v-if="titles != '修改班级'">
       <el-button @click="resetForm_class(ruleFormRef)">重置</el-button>
     </span>
     <span v-else>
      <el-button @click="centerDialogVisible = false">取消</el-button>
    </span>
   </el-form-item>
 </el-form>
 </el-dialog>
  <!-- 学生查询弹框 -->
  <el-dialog
   style="border-radius: var(--el-border-radius-base);"
   v-model="centerDialogVisible_student"
   :title="class_titles"
   width="1200"
   align-center>
   <div style="margin-left: 3.5%;">
       <span v-if="stuarray.length>0">
       <el-card style="max-width: 260px; display: inline-block;  margin: 5px;" v-for="stu in stuarray">

         <el-row :gutter="20">
           <el-tooltip content="删除学生" placement="top">
              <el-button link type="primary" icon="Close" @click="studentDelete(stu.userId)" v-hasPermi="['system:user:resetPwd']" style="position: relative; left: 225px; top: -30px;"></el-button>
           </el-tooltip>
        <span @click="student_Info(stu)"> <el-tooltip content="点击查看" placement="top"><el-avatar :size="50" :src="stu.avatar"/></el-tooltip></span>
        <el-text class="mx-1" style="position: relative; top: -6px; left: 5px">姓名：{{stu.nickname}}</el-text>
       </el-row>
       <el-link icon="edit" style="position: relative; left: 73%; top: 14.5px;" class="diaoban" @click="studentEdit(stu)">调班</el-link>
      </el-card>
      <el-pagination
      background
      v-model:current-page="currentPage4_01"
      v-model:page-size="pageSize4_01"
      :page-sizes="[5, 10, 20, 25]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total_01"
      @size-change="handleSizeChange_01"
      @current-change="handleCurrentChange_01"
      />
     </span>
     <span v-else>
       <el-empty description="该班级还没有学生哦~"/>
     </span>
   </div>
  </el-dialog>
   <!-- 学生调班查询弹框 -->
   <el-dialog
   style="border-radius: var(--el-border-radius-base);"
   v-model="centerDialogVisible_student_diaoban"
   :title="class_titles_student"
   width="300"
   align-center>
   <el-tree
    accordion="true"
    :data="deptOptions"
    :props="{ label: 'name', children: 'children',value:'id'}"
    :expand-on-click-node="true"
    node-key="id"
    highlight-current
    @node-click="handleNodeClick"
   />
<el-button @click="query_student_class">确认</el-button>
<el-button @click="centerDialogVisible_student_diaoban = false">取消</el-button>
   </el-dialog>
</template>

<script setup name="User">
import { getTokeName } from "@/utils/comstants";
import { reactive, ref, toRefs,watch } from "vue";
import { findAll_class,findStudentByClass,addOrUpdaclass,delclass,download,levelall,allteacher,changeclass,removestudent,findStage,findClassById } from "@/api/admin/class/class_api";
import { delBatchStudent,stu_list_tree } from "@/api/admin/student/student_api.js"
import { ElMessage,ElMessageBox,ElTree } from "element-plus";
import { useStudentStore1 } from "@/store/studentInfo";
import { useRouter } from 'vue-router';
const router = useRouter()

const queryRef=ref()
const ruleFormRef = ref()
const showSearch = ref(true); //动态隐藏
const classList = ref([]);//班级列表
const loading =ref(true)//页面加载
const currentPage4 = ref(1)
const pageSize4 = ref(5)
const total=ref(5)
const titles=ref('')
const class_titles = ref('')
const centerDialogVisible = ref(false);//新增修改弹框
const centerDialogVisible_student = ref(false)//学生查询弹框
const centerDialogVisible_student_diaoban = ref(false)//学生调班
const class_titles_student = ref("选择要调换班级")//学生调班提示
const teachercities = ref([])//讲师数组
const levelIdcities = ref([])//阶段数组
const deptOptions=ref([]) //三级菜单
//要查询的班级的参数
const queryParams = ref({
   pageNum:currentPage4.value,
   pageSize:pageSize4.value,
   nickname:'',
   phone:'',
   className:'',
   classId:'',
})

//属性查询方法
function treefunlist(){
  loading.value=true
 stu_list_tree().then(res=>{
  loading.value=false
   deptOptions.value=res.data.obj
 })
}
const cacheData = ref([])  //懒加载

cacheData_tree()
function cacheData_tree(){
   stu_list_tree().then(res=>{
  cacheData.value=res.data.obj[0].children
})
}



const datanum = []  
const class_info = ref()
//多选
const handleSelectionChange = (val) => {
   datanum.splice(0,datanum.length);
   val.forEach(element => {
       datanum.push(element.classId)
   });
   //说明用户选择1条数据
   if(datanum.length == 1){
       class_info.value=val
   }
}


//查询列表
function getList(){
  loading.value = true
  findAll_class(queryParams.value).then(res=>{
     loading.value = false
     classList.value=res.data.obj.list
     total.value=res.data.obj.total
     classList.value.forEach(element => {
        //创建时间格式化
     if(element.createTime !=null){
      element.createTime=caseTime(element.createTime)
     }
     //修改时间格式化
     if(element.updateTime !=null){
      element.updateTime=caseTime(element.updateTime)
     }
     });
  })
}
//添加或修改数据
const ruleForm = ref({
   className: '',
   levelId: '',         //阶段外键
   teacherId: '',        //讲师外键
   lpId:''               //具体专业几
})

const rules = reactive({
   className: [{ required: true, message: '班级名不能为空', trigger: 'blur' },],
   levelId: [{ required: true, message: '阶段不能为空', trigger: 'blur' },],
   lpId: [{ required: true, message: '具体阶段不能为空', trigger: 'blur' },],
})

//搜索重置
const resetQuery = (formEl) => {
  queryParams.value.className=null
  queryParams.value.nickname=null
  queryParams.value.phone=null
 if (!formEl) return
 formEl.resetFields() 
 //让班级id为空
 getList()
}

//新增初始化方法
function handleAdd(){
  ruleForm.value={}//清空
  centerDialogVisible.value=true
  titles.value='新增班级';
}
//修改初始化方法
function handleUpdate(row){
  ruleForm.value={}//清空
 
  if(datanum.length == 1){
      centerDialogVisible.value=true
      titles.value='修改班级';
     lpIdcitiesfun(class_info.value[0].levelId)//同步专业阶段
     ruleForm.value=class_info.value[0]
  }else if(row.classId != null){
     lpIdcitiesfun(row.levelId)//同步专业阶段
     centerDialogVisible.value=true
     titles.value='修改班级';
     ruleForm.value=row
  }else{
     ElMessage.warning("请选择一个班级哦")
  }
}

//添加和修改
function submitForm_class(formEl){
  if (!formEl) return
 formEl.validate((valid) => {
   if (valid) {
   if(ruleForm.value.teacherId == undefined){
     ruleForm.value.teacherId=-1   //代表没有老师带班
   }
   addOrUpdaclass(ruleForm.value).then(res=>{
        if(res.data.code == 200){
           centerDialogVisible.value=false
            ElMessage.success('操作成功');
            cacheData_tree();
            getList();
        }else{
           ElMessage.error(res.data.message)
        }
     })
   } 
 })
}

//删除方法
function handleDelete(row){
  ElMessageBox.confirm(
   '您确认要删除嘛?',
   '温馨提示',
   {
     confirmButtonText: '确认',
     cancelButtonText: '取消',
     type: 'warning',
   }
 )
   .then(() => {
    if(datanum.length>0){    //删除方法
       delclass(datanum).then(res=>{
        if(res.data.code == 200){
           ElMessage.success("删除成功");
           getList();
           cacheData_tree()
        }else{
          ElMessage.error("删除失败");
        }
     })
    }else if(row.classId != null){
          let arr = []
          arr.push(row.classId)
       delclass(arr).then(res=>{
           arr.splice(0,arr.length)//清空数组
        if(res.data.code == 200){
           ElMessage.success("删除成功");
           getList();
           cacheData_tree()
        }else{
          ElMessage.error("删除失败");
        }
     })
    }else{
     ElMessage.warning("请至少选择一个")
    }
    
   })
   .catch(() => {
     ElMessage({
       type: 'info',
       message: '已取消删除',
     })
   })
}

//导出方法
function handleExport(){
    download().then(res=>{
     const xlsx = "application/vnd.ms-excel";
     let blob = new Blob([res.data],{type:xlsx})
       const enlink = document.createElement('a')
       enlink.download='学生模板.xlsx';
       enlink.style.display='none',
       enlink.href = URL.createObjectURL(blob)
       document.body.appendChild(enlink);
       enlink.click();
       URL.revokeObjectURL(enlink.href);
       document.body.removeChild(enlink)
    })
}

//控制条数
const handleSizeChange = (val) => {
   queryParams.value.pageSize=val
   getList()
}
//控制页数
const handleCurrentChange = (val) => {
   queryParams.value.pageNum=val
   getList()
}


//重置添加或者修改
const resetForm_class = (formEl) => {
  ruleForm.value = {}
 if (!formEl) return
 formEl.resetFields()
}

/**时间转换 */
function caseTime(date){
   let time=new Date(date);
   let year=time.getFullYear();
   let month=time.getMonth()+1;
   let day=time.getDate()+1;
   let hours=time.getHours();
   let minutes=time.getMinutes();
   if(month<=9){
       month='0'+month
   }

   if(day<=9){
      day='0'+day
   }

   if(hours<=9){
     hours='0'+hours
   }
   if(minutes<=9){
     minutes='0'+minutes
   }
   return year+"-"+month+"-"+day+" "+hours+":"+minutes;
}
//阶段查询所有
function level_list(){
   levelall().then(res=>{
   levelIdcities.value=res.data.obj
  })
}
//老师查询所有
function teacher_list(){
  allteacher().then(res=>{
   teachercities.value=res.data.obj
  })
}

const props = defineProps({
  /* 是否显示检索条件 */
  showSearch: {
     type: Boolean,
     default: true,
  },
  /* 显隐列信息 */
  columns: {
     type: Array,
  },
  /* 是否显示检索图标 */
  search: {
     type: Boolean,
     default: true,
  },
  /* 显隐列类型（transfer穿梭框、checkbox复选框） */
  showColumnsType: {
     type: String,
     default: "checkbox",
  },
  /* 右外边距 */
  gutter: {
     type: Number,
     default: 10,
  },
})

const emits = defineEmits(['update:showSearch', 'queryTable']);

// 搜索
function toggleSearch() {
 if (showSearch.value == true) {
    showSearch.value = false
 } else {
    showSearch.value = true
 }
 emits("update:showSearch", !props.showSearch);
}


//根据班级id查询旗下学生信息

const  stuarray = ref([])
const total_01 = ref()
const currentPage4_01 = ref(1)
const pageSize4_01 = ref(8)
const sel_classByid = ref()
/*学生个人信息分页*/
const class_studeninfo = ref({
   pageNum:currentPage4_01.value,
   pageSize:pageSize4_01.value,
   classId:''
})

function classonclick(row){
   if(row.nickname == null){
    class_titles.value=row.className+"班学生 (●'◡'●) 【带班讲师：暂无老师】📖 【目前阶段："+row.name+"】"
   }else{
    class_titles.value=row.className+"班学生 😯 【带班讲师："+row.nickname+"】📖 【目前阶段："+row.name+"】"
   }
   currentPage4_01.value=1
   pageSize4_01.value=8
   class_studeninfo.value.pageNum=1
   class_studeninfo.value.pageSize=8
   class_studeninfo.value.classId=row.classId
     classfindall()
    sel_classByid.value=row.classId
   centerDialogVisible_student.value=true  //打开弹框
}

function classfindall(){
   loading.value=true
   findStudentByClass(class_studeninfo.value).then(res=>{
      loading.value=false   
        if(res.data.code == 200){
           stuarray.value=res.data.obj.list
           total_01.value=res.data.obj.total
        }
})
}

const handleSizeChange_01 = (val) => {
   class_studeninfo.value.pageSize=val
   classfindall()
}
const handleCurrentChange_01 = (val) => {
   class_studeninfo.value.pageNum=val
   classfindall()
}
const studentparam=ref({
  pageNum:1,
  pageSize:5,
})

//删除学生
function studentDelete(id){
  ElMessageBox.confirm(
   '您确认要删除嘛?',
   '温馨提示',
   {
     confirmButtonText: '确认',
     cancelButtonText: '取消',
     type: 'warning',
   }).then(() => {
     removestudent(id).then(res=>{
        if(res.data.code == 200){
           ElMessage.success("删除成功");
           stuarray.value=[] //刷新
           //刷新学生数组
           findClassById(sel_classByid.value).then(res=>{
           stuarray.value=res.data.obj
        })
        }else{
          ElMessage.error("删除失败");
        }
     })
   })
   .catch(() => {
     ElMessage({
       type: 'info',
       message: '已取消删除',
     })
   })
}
const userId = ref()
//学生换班
function studentEdit(row){
   treefunlist()
   userId.value=row.userId
   centerDialogVisible_student_diaoban.value=true
}
const classId = ref()
//阶段名称根据班级查询学生方法
function handleNodeClick(data){
  if(data.id != 1 && data.id != 2 && data.id != 3 && data.id != 4){
     classId.value=data.classId   //赋值班级id
  }
}

/*确认调班方法*/
function query_student_class(){
  changeclass(userId.value,classId.value).then(res=>{
     if(res.data.code == 200){
        ElMessage.success("调班成功");
        centerDialogVisible_student_diaoban.value=false//关闭弹框
         //刷新学生数组
         findClassById(sel_classByid.value).then(res=>{
           stuarray.value=res.data.obj
        })
     }else{
        ElMessage.error(res.data.message)
     }
  })
}

/*学生个人信息查询*/
function student_Info(row){

     useStudentStore1().setStudentInfo(row)
     router.push("/teacher/studentInfo")
}


//查询具体专业几
const ff = ref([])
function lpIdcitiesfun(id){
  findStage(id).then(res=>{
     ff.value=res.data.obj
  })
}


// 刷新
function refresh() {
   // alert(111)
 getList()
}

getList()
level_list()
teacher_list()

</script>
<style>
.button_clss{
  width: 73px;
  height: 28px;
}
.el-card__body{
   width: 260px;
}
.diaoban{
   color: #79bbff;
}
.diaoban:hover{
   color: rgb(255, 0, 0);
}
.class_style{
  color:  #eebe77;
}
.class_style:hover{
  color:  #606266;
}
</style>
